package uk.co.droidinactu.sony.prst1.home.db;

import java.io.File;

import uk.co.droidinactu.sony.prst1.home.SonyPrsT1HomeActivity;
import uk.co.droidinactu.sony.prst1.home.data.AbstractDataObj;
import android.content.Context;
import android.database.Cursor;
import android.database.MergeCursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * 
 * @author andy
 */
public final class SonyDatabaseController {
	private static final String DATABASE_NAME = "books.db";
	private static final String DATABASE_PATH_EXT = "/mnt/extsd/Sony_Reader/database/";
	private static final String DATABASE_PATH_INT = "/mnt/sdcard/Sony_Reader/database/";
	private static final String LOG_TAG = "SonyDatabaseController";

	private SQLiteDatabase myDBExt = null;
	private SQLiteDatabase myDBInt = null;

	public SonyDatabaseController(final Context context) {
		super();
	}

	public void close() {
		if (myDBInt != null) {
			myDBInt.close();
			myDBInt = null;
		}
		if (myDBExt != null) {
			myDBExt.close();
			myDBExt = null;
		}
	}

	/**
	 * 
	 * @param sql
	 * @param selectionArgs
	 * @return
	 */
	public Cursor execSql(final String sql, final String[] selectionArgs) {
		Cursor retCrsr = null;
		Cursor crsr1 = null;
		Cursor crsr2 = null;
		try {
			if (myDBInt != null) {
				crsr1 = myDBInt.rawQuery(sql, selectionArgs);
				if (myDBExt != null) {
					crsr2 = myDBExt.rawQuery(sql, selectionArgs);
					retCrsr = new MergeCursor(new Cursor[] { crsr1, crsr2 });
				} else {
					retCrsr = crsr1;
				}
			}
		} catch (Exception e) {
			Log.e(SonyPrsT1HomeActivity.LOG_TAG, LOG_TAG + "Exception executing sqlite.rawQuery [" + sql
					+ "]", e);
		}
		return retCrsr;
	}

	/**
	 * Return a Cursor over the list of all todo in the database
	 * 
	 * @return Cursor over all notes
	 */
	public Cursor getAll(final AbstractDataObj obj) {
		return getAll(obj.getTableName(), null, null, null, null, null, null);
	}

	public Cursor getAll(final String table, final String[] columns, final String selection,
			final String[] selectionArgs, final String groupBy, final String having, final String orderBy) {
		return getAll(table, columns, selection, selectionArgs, groupBy, having, orderBy, null);
	}

	/**
	 * 
	 * @param table
	 *            The table name to compile the query against.
	 * @param columns
	 *            A list of which columns to return. Passing null will return
	 *            all columns, which is discouraged to prevent reading data from
	 *            storage that isn't going to be used.
	 * @param selection
	 *            A filter declaring which rows to return, formatted as an SQL
	 *            WHERE clause (excluding the WHERE itself). Passing null will
	 *            return all rows for the given table.
	 * @param selectionArgs
	 *            You may include ?s in selection, which will be replaced by the
	 *            values from selectionArgs, in order that they appear in the
	 *            selection. The values will be bound as Strings.
	 * @param groupBy
	 *            A filter declaring how to group rows, formatted as an SQL
	 *            GROUP BY clause (excluding the GROUP BY itself). Passing null
	 *            will cause the rows to not be grouped.
	 * @param having
	 *            A filter declare which row groups to include in the cursor, if
	 *            row grouping is being used, formatted as an SQL HAVING clause
	 *            (excluding the HAVING itself). Passing null will cause all row
	 *            groups to be included, and is required when row grouping is
	 *            not being used.
	 * @param orderBy
	 *            How to order the rows, formatted as an SQL ORDER BY clause
	 *            (excluding the ORDER BY itself). Passing null will use the
	 *            default sort order, which may be unordered.
	 * @param limit
	 *            Limits the number of rows returned by the query, formatted as
	 *            LIMIT clause. Passing null denotes no LIMIT clause.
	 * @return
	 */
	public Cursor getAll(final String table, final String[] columns, final String selection,
			final String[] selectionArgs, final String groupBy, final String having, final String orderBy,
			final String limit) {
		Cursor retCrsr = null;
		Cursor crsr1 = null;
		Cursor crsr2 = null;
		try {
			if (myDBInt != null) {
				crsr1 = myDBInt.query(table, columns, selection, selectionArgs, groupBy, having, orderBy,
						limit);
				if (myDBExt != null) {
					crsr2 = myDBExt.query(table, columns, selection, selectionArgs, groupBy, having, orderBy,
							limit);
					retCrsr = new MergeCursor(new Cursor[] { crsr1, crsr2 });
				} else {
					retCrsr = crsr1;
				}
			}
		} catch (Exception e) {
			Log.e(SonyPrsT1HomeActivity.LOG_TAG, LOG_TAG + "Exception executing sqlite.query on table ["
					+ table + "]", e);
		}
		return retCrsr;
	}

	public void open() {
		final File dbFile = new File(DATABASE_PATH_INT + DATABASE_NAME);
		if (dbFile.exists()) {
			myDBInt = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null,
					SQLiteDatabase.OPEN_READONLY);
		}
		final File dbFile2 = new File(DATABASE_PATH_EXT + DATABASE_NAME);
		if (dbFile2.exists()) {
			myDBExt = SQLiteDatabase.openDatabase(dbFile2.getAbsolutePath(), null,
					SQLiteDatabase.OPEN_READONLY);
		}
	}
}
